// localStorage ==> code
// 顯示 ====> hook_name + descriptor + 修改 + 刪除
// 顯示 ====> 添加hook功能
(() => {
    var add_options = document.createElement('a');
    add_options.addEventListener('click', () => {
        window.open(chrome.extension.getURL("back.html"))
    });
    add_options.textContent = '添加hook代码';
    add_options.style.width = '30px';
    add_options.style.height = '30px';
    document.body.append(add_options);
    chrome.storage.sync.get(['code'], (e) => {
        var content = e;
        if(!content.code)return;
        if (Object.values(content.code).every((e)=>{return (e==null)})) return;
        var tar = document.createElement('table');
        tar.innerHTML = `
			<caption>HOOK ITEMS</caption>
			<!--第一行-->
			<tr>
				<td>name</td>
				<td>desc</td>
				<td>state</td>
				<td>delete</td>
			</tr>     
            `
        content.code.forEach((element, id) => {
            // 内部禁止修改content,使用浅拷贝
            if(!element)return;
            var tar_tr = document.createElement('tr')
            for (var i = 1; i < 5; i++) {
                var a = document.createElement('td');
                if (i == 1) {
                    a.textContent = element.name;
                    a.addEventListener('click', () => {
                        chrome.storage.sync.set({ 'hook_id': id+1 }, () => { });
                        window.open(chrome.extension.getURL("back.html"))
                    })
                };
                if (i == 2) {
                    a.textContent = element.desc;
                };
                if (i == 3) {
                    a.textContent = element.state;
                    var state = a;
                    state.addEventListener('click', () => {
                        if (parseInt(state.textContent)) {
                            state.textContent = 0;
                            var content_ = content.code.slice();
                            content_[id].state = 0;
                            chrome.storage.sync.set({ 'code': content_ }, () => { });
                        } else {
                            state.textContent = 1;
                            var content_ = content.code.slice();
                            content_[id].state = 1;
                            chrome.storage.sync.set({ 'code': content_ }, () => { });
                        };
                    });
                };
                if (i == 4) {
                    a.textContent = 'delete';
                    a.addEventListener('click', () => {
                        var content_ = content.code.slice();
                        delete content_[id];
                        chrome.storage.sync.set({ 'code': content_ }, () => { });
                        location.reload();
                    });
                };
                tar_tr.append(a);
            };
            tar.append(tar_tr);
        });
        document.body.append(tar);
    });
})();